package rabbitas {
	
	import rabbitas.attributes.MethodName;
	import rabbitas.attributes.AttributeName;
	/**
	 * @author martindyrby
	 */
	public class InstanceDecorator {
		public var instanceManager : InstanceManager;
		public function decorateFromAttributes(def : XML, instance : *) : void {
			var attributes:XMLList = def.attributes();
			var numAttributes:uint = attributes.length();

			var i:int;
			
			for(i = 0; i < numAttributes; ++i) {
				var attribute : XML = attributes[i];
				var name : String = attribute.name();
				var value : String = def.@[name];
				
				if(!AttributeName.isFrameworkAttribute(name) && !EventManager.isEventAttribute(name)) {
					instance[name]=Reflector.reflectStringValue(value,instanceManager);
				}
			}
		}

		public function decorateFromChildren(def : XML, instance : *) : void {
			var children:XMLList = def.children();
			var numChildren: uint = children.length();
			
			if(def.hasSimpleContent()) {
				var defText:String = def.text();
				if(defText != '') {
					var f:Function;
					try {
						f = instance[MethodName.ADD_CHILD];
						f.apply(null, defText);
					} catch (e:Error) {
						RabbitLogger.debug(e);
						try {
							f = instance[MethodName.ADD_CHILD_DATA];
							f.apply(null, defText);
						} catch (e:Error) {
							RabbitLogger.debug(e);
						}					
					}
				}	
			} else {
				for(var i:int = 0;i < numChildren;++i) {
					var child : XML = children[i];
					RabbitLogger.debug('child',child.toXMLString());
					
					if (PropertyResolver.isProperty(child)) {
						instance[child.@name] = PropertyResolver.resolveValue(child, instanceManager);

					} else if(!MethodInvoker.isConstructor(child) && !MethodInvoker.isMethod(child)){
						var fa:Function = instance[MethodName.ADD_CHILD];
						var fad:Function = instance[MethodName.ADD_CHILD_DATA];

						if (fa != null) {
							fa.apply(null, instanceManager.getObjectById(child.@[AttributeName.ID]));
						}else if(fad != null) {
							fad.apply(null, instanceManager.getObjectById(child.@[AttributeName.ID]));
						}
					}
				}	
			}
		}
	}
}
